﻿using System;
using System.Linq;
using System.Threading.Tasks;
using Coravel.Invocable;
using CRM.Extensions;
using CRM.Models.Email;
using CRM.Services.Email;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;

namespace CRM.Jobs
{
    public class TimingSendEmailJob : IInvocable
    {
        private readonly MailjetApplicationService _service;
        private readonly MyDbContext _dbContext;
        private readonly ILogger<TimingSendEmailJob> _logger;
        private readonly RushMailApplicationService _rushMailApplicationService;

        public TimingSendEmailJob(MailjetApplicationService service, MyDbContext dbContext, ILogger<TimingSendEmailJob> logger, RushMailApplicationService rushMailApplicationService)
        {
            _service = service;
            _dbContext = dbContext;
            _logger = logger;
            _rushMailApplicationService = rushMailApplicationService;
        }
        public async Task Invoke()
        {
            var ceilCurrentMinute = DateTime.Now.CurrentMinute().AddMinutes(1);
            var eligibleTasks = await _dbContext.EmailMarketing
                .Where(m => m.State == EmailMarketing.StateEnum.Submitted) // 已提交
                .Where(m => m.Type == EmailMarketing.TypeEnum.Server) // 服务器发送
                .Where(m => m.TimingTransmission <= ceilCurrentMinute)
                .OrderBy(m => m.SendingNum)
                .ToListAsync();
            _logger.LogInformation("定时邮件任务数量:{EligibleTasksCount}", eligibleTasks.Count);

            foreach (var task in eligibleTasks)
            {
                BackgroundQueue.Queue.Enqueue(task);
            }
        }
    }
}